<?php
/**
 * Add a new Proffessional Experience
 *
 * @author Xavier VILAIN
 */
use Hive\Company;
use Fox\Core\Errors;
use Fox\Generator;
use Hive\Ressource;
use Hive\Ressource\Experience;
use Fox\Popup;
use Fox\Html\Screen;

$xview = Xview::instance();
$rid = $xview->val('rid');
$screen = new Screen('sJob','add',null,true,Generator::ajaxReload('contentCol',
			Generator::url('ressource','jobs',null,array('rid' => $rid))));
$block = $xview->component('ressource','job');
$screen->add($block)->noLegend();
$screen->buttons('add')->tabIndex = 9;
if($screen->submitted()) {

	$fields = $screen->get();
	if(!$screen->errors()) {
		try {

			$fields['current'] = 0;
			// Check if the Company Exist
			if(!empty($fields['companyName']))
			{
				$company = Company::lookup($fields['companyName']);
				if(!$company)
				{
					$company = new Company();
					$company->setFields(array('company_name' => $fields['companyName']));
					$company->create();
				}
				$fields['compid'] = $company->getId();
			}

			/* @var $contact Hive\Ressource */
			$contact = Xview::instance()->component('ressource', 'object');
			$experience = new Experience();
			$fields['ressource_id'] = $rid;
			$experience->setFields($fields);
			$contact->addToExperiences($experience);
			// Update Current Experience Flag
			$start_date = null;
			foreach($contact->experiences() as $experience) {
				$current = $experience->current;
				if($experience->start_date > $start_date ) {
					$start_date = $experience->start_date;
					$currentExperience = $experience;
				}
				if($current) {
					$oldCurrentExperience = $experience; 
				}
			}
			if(empty($oldCurrentExperience) || $currentExperience->expid != $oldCurrentExperience->expid) {
				if(!empty($oldCurrentExperience)) {
					$oldCurrentExperience->current = 0;
					$contact->replaceExperiences($oldCurrentExperience);
				}
				$currentExperience->current = 1;
				$contact->replaceExperiences($currentExperience);
			}
			$contact->prepareUpdate(Ressource::CHANGE_EXPERIENCE_ADD);
			$contact->update();
			Fox\Message::Success(Msg(\Fox\Msg::BUNDLE,\Fox\Msg::MSG_CREATE,utf8_decode($fields['jobtitle'])));
			
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Fox\Message::Error($e);
		}
		catch (Fox\Object\Exception\NotExist $e)
		{
			Fox\Message::Error($e);
		}
		catch (Exception $e)
		{
			Fox\Message::Error($e);
		}
		
	}
	return $xview->messages(true,true);
}
$popup = new Popup('add',Msg(Hive::BUNDLE,Hive::MSG_ADD_A_NEW_JOB),$screen,700);
return $popup->display();